import { Sequelize } from "sequelize-typescript";
import DataModel from '../model/data'
import DateRecord from '../model/date'
import StatusModel from '../model/status'
import UserModel from '../model/user'
import MsgModel from '../model/msg'
import { dbLogger, logger } from "./log";

// 全局sequelize实例
let sequelize: Sequelize;

const initDatabase = (dbPath: string, isWorker = false) => {
    // 根据进程类型优化连接池配置
    const poolConfig = isWorker ? {
        min: 0,
        max: 5,  // Worker进程使用较小连接池
        idle: 10000,
        acquire: 30000,
        evict: 1000
    } : {
        min: 0,
        max: 20, // 主进程使用较大连接池
        idle: 10000,
        acquire: 30000,
        evict: 1000
    };
    
    sequelize = new Sequelize({
        host: 'localhost',
        dialect: 'sqlite',
        storage: dbPath,
        logging: isWorker ? false : (sql) => dbLogger.info(sql), // Worker进程关闭SQL日志
        pool: poolConfig
    })
    // 添加数据库模型
    sequelize.addModels([DataModel, DateRecord, StatusModel, UserModel, MsgModel]);
    // 判断数据库是否初始化
    sequelize.authenticate().then(() => {
        logger.info('Connection has been established successfully.')
    })
    .catch(err => {
        logger.error('Unable to connect to the database:', err)
    });

    // 同步本地数据库
    sequelize.sync().then(res => {
        logger.info("同步数据库成功")
    })
}

export {DataModel,DateRecord,StatusModel,UserModel,MsgModel, initDatabase, sequelize}
